using Microsoft.EntityFrameworkCore;
using SheLife.Domain.Entities;
using SheLife.Infrastructure.Data;

namespace SheLife.Infrastructure.Repositories
{
    /// <summary>
    /// 目标仓储实现
    /// </summary>
    public class GoalRepository : Repository<Goal>, IGoalRepository
    {
        public GoalRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<Goal>> GetByUserIdAsync(Guid userId)
        {
            return await _dbSet.Where(g => g.UserId == userId).OrderByDescending(g => g.CreatedAt).ToListAsync();
        }

        public async Task<IEnumerable<Goal>> GetByUserIdAndCategoryAsync(Guid userId, string category)
        {
            return await _dbSet.Where(g => g.UserId == userId && g.Category == category).ToListAsync();
        }

        public async Task<IEnumerable<Goal>> GetByUserIdAndStatusAsync(Guid userId, string status)
        {
            return await _dbSet.Where(g => g.UserId == userId && g.Status == status).ToListAsync();
        }

        public async Task<IEnumerable<Goal>> GetByUserIdAndLifeStageAsync(Guid userId, string lifeStage)
        {
            return await _dbSet.Where(g => g.UserId == userId && g.LifeStage == lifeStage).ToListAsync();
        }

        public async Task<IEnumerable<Goal>> GetInProgressAsync(Guid userId)
        {
            return await _dbSet.Where(g => g.UserId == userId && g.Status == "in_progress").ToListAsync();
        }

        public async Task<IEnumerable<Goal>> GetCompletedAsync(Guid userId)
        {
            return await _dbSet.Where(g => g.UserId == userId && g.Status == "completed").ToListAsync();
        }

        public async Task<Dictionary<string, int>> GetCategoryStatisticsAsync(Guid userId)
        {
            var goals = await _dbSet
                .Where(g => g.UserId == userId)
                .GroupBy(g => g.Category)
                .Select(g => new { Category = g.Key, Count = g.Count() })
                .ToListAsync();

            return goals.ToDictionary(g => g.Category, g => g.Count);
        }

        public async Task<Dictionary<string, int>> GetStatusStatisticsAsync(Guid userId)
        {
            var goals = await _dbSet
                .Where(g => g.UserId == userId)
                .GroupBy(g => g.Status)
                .Select(g => new { Status = g.Key, Count = g.Count() })
                .ToListAsync();

            return goals.ToDictionary(g => g.Status, g => g.Count);
        }

        public async Task<Dictionary<string, double>> GetProgressStatisticsAsync(Guid userId)
        {
            var goals = await _dbSet.Where(g => g.UserId == userId).ToListAsync();

            var result = new Dictionary<string, double>();
            if (goals.Any())
            {
                result["AverageProgress"] = goals.Average(g => g.ProgressPercentage);
                result["TotalGoals"] = goals.Count;
                result["CompletedGoals"] = goals.Count(g => g.Status == "completed");
                result["InProgressGoals"] = goals.Count(g => g.Status == "in_progress");
                result["NotStartedGoals"] = goals.Count(g => g.Status == "not_started");
            }

            return result;
        }
    }

    /// <summary>
    /// 目标里程碑仓储实现
    /// </summary>
    public class GoalMilestoneRepository : Repository<GoalMilestone>, IGoalMilestoneRepository
    {
        public GoalMilestoneRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<GoalMilestone>> GetByGoalIdAsync(Guid goalId)
        {
            return await _dbSet.Where(m => m.GoalId == goalId).OrderBy(m => m.DueDate).ToListAsync();
        }

        public async Task<IEnumerable<GoalMilestone>> GetByUserIdAsync(Guid userId)
        {
            var goalIds = await _context.Set<Goal>()
                .Where(g => g.UserId == userId)
                .Select(g => g.Id)
                .ToListAsync();

            return await _dbSet.Where(m => goalIds.Contains(m.GoalId)).OrderBy(m => m.DueDate).ToListAsync();
        }

        public async Task<IEnumerable<GoalMilestone>> GetByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var goalIds = await _context.Set<Goal>()
                .Where(g => g.UserId == userId)
                .Select(g => g.Id)
                .ToListAsync();

            return await _dbSet
                .Where(m => goalIds.Contains(m.GoalId) && m.DueDate >= startDate && m.DueDate <= endDate)
                .OrderBy(m => m.DueDate)
                .ToListAsync();
        }

        public async Task<IEnumerable<GoalMilestone>> GetUpcomingAsync(Guid userId, int days = 7)
        {
            var thresholdDate = DateTime.UtcNow.AddDays(days);
            var goalIds = await _context.Set<Goal>()
                .Where(g => g.UserId == userId)
                .Select(g => g.Id)
                .ToListAsync();

            return await _dbSet
                .Where(m => goalIds.Contains(m.GoalId) && m.DueDate <= thresholdDate && !m.IsCompleted)
                .OrderBy(m => m.DueDate)
                .ToListAsync();
        }

        public async Task<IEnumerable<GoalMilestone>> GetOverdueAsync(Guid userId)
        {
            var today = DateTime.UtcNow.Date;
            var goalIds = await _context.Set<Goal>()
                .Where(g => g.UserId == userId)
                .Select(g => g.Id)
                .ToListAsync();

            return await _dbSet
                .Where(m => goalIds.Contains(m.GoalId) && m.DueDate < today && !m.IsCompleted)
                .OrderBy(m => m.DueDate)
                .ToListAsync();
        }

        public async Task<Dictionary<Guid, int>> GetCompletionRateByGoalAsync(IEnumerable<Guid> goalIds)
        {
            var milestones = await _dbSet
                .Where(m => goalIds.Contains(m.GoalId))
                .ToListAsync();

            var result = new Dictionary<Guid, int>();
            foreach (var goalId in goalIds)
            {
                var goalMilestones = milestones.Where(m => m.GoalId == goalId).ToList();
                if (goalMilestones.Any())
                {
                    var completedCount = goalMilestones.Count(m => m.IsCompleted);
                    var totalCount = goalMilestones.Count;
                    result[goalId] = totalCount > 0 ? (int)((double)completedCount / totalCount * 100) : 0;
                }
                else
                {
                    result[goalId] = 0;
                }
            }

            return result;
        }
    }

    /// <summary>
    /// 习惯仓储实现
    /// </summary>
    public class HabitRepository : Repository<Habit>, IHabitRepository
    {
        public HabitRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<Habit>> GetByUserIdAsync(Guid userId)
        {
            return await _dbSet.Where(h => h.UserId == userId).OrderByDescending(h => h.CreatedAt).ToListAsync();
        }

        public async Task<IEnumerable<Habit>> GetByUserIdAndCategoryAsync(Guid userId, string category)
        {
            return await _dbSet.Where(h => h.UserId == userId && h.Category == category).ToListAsync();
        }

        public async Task<IEnumerable<Habit>> GetByUserIdAndStatusAsync(Guid userId, string status)
        {
            return await _dbSet.Where(h => h.UserId == userId && h.Status == status).ToListAsync();
        }

        public async Task<IEnumerable<Habit>> GetActiveAsync(Guid userId)
        {
            return await _dbSet.Where(h => h.UserId == userId && h.Status == "active").ToListAsync();
        }

        public async Task<IEnumerable<Habit>> GetByUserIdAndLifeStageAsync(Guid userId, string lifeStage)
        {
            return await _dbSet.Where(h => h.UserId == userId && h.LifeStage == lifeStage).ToListAsync();
        }

        public async Task<Dictionary<string, int>> GetCategoryStatisticsAsync(Guid userId)
        {
            var habits = await _dbSet
                .Where(h => h.UserId == userId)
                .GroupBy(h => h.Category)
                .Select(h => new { Category = h.Key, Count = h.Count() })
                .ToListAsync();

            return habits.ToDictionary(h => h.Category, h => h.Count);
        }

        public async Task<Dictionary<string, int>> GetStatusStatisticsAsync(Guid userId)
        {
            var habits = await _dbSet
                .Where(h => h.UserId == userId)
                .GroupBy(h => h.Status)
                .Select(h => new { Status = h.Key, Count = h.Count() })
                .ToListAsync();

            return habits.ToDictionary(h => h.Status, h => h.Count);
        }

        public async Task<Dictionary<string, double>> GetStreakStatisticsAsync(Guid userId)
        {
            var habits = await _dbSet.Where(h => h.UserId == userId).ToListAsync();

            var result = new Dictionary<string, double>();
            if (habits.Any())
            {
                result["AverageStreak"] = habits.Average(h => h.CurrentStreak);
                result["MaxStreak"] = habits.Max(h => h.MaxStreak);
                result["TotalHabits"] = habits.Count;
                result["ActiveHabits"] = habits.Count(h => h.Status == "active");
            }

            return result;
        }
    }

    /// <summary>
    /// 习惯记录仓储实现
    /// </summary>
    public class HabitRecordRepository : Repository<HabitRecord>, IHabitRecordRepository
    {
        public HabitRecordRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<HabitRecord>> GetByHabitIdAsync(Guid habitId)
        {
            return await _dbSet.Where(r => r.HabitId == habitId).OrderByDescending(r => r.RecordDate).ToListAsync();
        }

        public async Task<IEnumerable<HabitRecord>> GetByUserIdAsync(Guid userId)
        {
            var habitIds = await _context.Set<Habit>()
                .Where(h => h.UserId == userId)
                .Select(h => h.Id)
                .ToListAsync();

            return await _dbSet.Where(r => habitIds.Contains(r.HabitId)).OrderByDescending(r => r.RecordDate).ToListAsync();
        }

        public async Task<IEnumerable<HabitRecord>> GetByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var habitIds = await _context.Set<Habit>()
                .Where(h => h.UserId == userId)
                .Select(h => h.Id)
                .ToListAsync();

            return await _dbSet
                .Where(r => habitIds.Contains(r.HabitId) && r.RecordDate >= startDate && r.RecordDate <= endDate)
                .OrderBy(r => r.RecordDate)
                .ToListAsync();
        }

        public async Task<HabitRecord?> GetByHabitIdAndDateAsync(Guid habitId, DateTime date)
        {
            return await _dbSet.FirstOrDefaultAsync(r => r.HabitId == habitId && r.RecordDate.Date == date.Date);
        }

        public async Task<Dictionary<DateTime, int>> GetDailyCompletionCountAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow.Date;
            var startDate = endDate.AddDays(-days);

            var habitIds = await _context.Set<Habit>()
                .Where(h => h.UserId == userId)
                .Select(h => h.Id)
                .ToListAsync();

            var records = await _dbSet
                .Where(r => habitIds.Contains(r.HabitId) && r.RecordDate >= startDate && r.RecordDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<DateTime, int>();
            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                var dayRecords = records.Where(r => r.RecordDate.Date == date.Date);
                result[date] = dayRecords.Count();
            }

            return result;
        }

        public async Task<Dictionary<Guid, double>> GetCompletionRateByHabitAsync(IEnumerable<Guid> habitIds, int days = 30)
        {
            var endDate = DateTime.UtcNow.Date;
            var startDate = endDate.AddDays(-days);

            var records = await _dbSet
                .Where(r => habitIds.Contains(r.HabitId) && r.RecordDate >= startDate && r.RecordDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<Guid, double>();
            foreach (var habitId in habitIds)
            {
                var habitRecords = records.Where(r => r.HabitId == habitId).ToList();
                var totalDays = (endDate - startDate).Days + 1;
                var completedDays = habitRecords.Count;
                result[habitId] = totalDays > 0 ? (double)completedDays / totalDays * 100 : 0;
            }

            return result;
        }

        public async Task<Dictionary<Guid, int>> GetCurrentStreaksAsync(IEnumerable<Guid> habitIds)
        {
            var records = await _dbSet
                .Where(r => habitIds.Contains(r.HabitId))
                .OrderBy(r => r.RecordDate)
                .ToListAsync();

            var result = new Dictionary<Guid, int>();
            foreach (var habitId in habitIds)
            {
                var habitRecords = records.Where(r => r.HabitId == habitId).ToList();
                var streak = 0;
                var currentDate = DateTime.UtcNow.Date;

                // 从今天开始倒推，检查连续的记录
                while (habitRecords.Any(r => r.RecordDate.Date == currentDate))
                {
                    streak++;
                    currentDate = currentDate.AddDays(-1);
                }

                result[habitId] = streak;
            }

            return result;
        }
    }

    /// <summary>
    /// 学习计划仓储实现
    /// </summary>
    public class LearningPlanRepository : Repository<LearningPlan>, ILearningPlanRepository
    {
        public LearningPlanRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<LearningPlan>> GetByUserIdAsync(Guid userId)
        {
            return await _dbSet.Where(p => p.UserId == userId).OrderByDescending(p => p.CreatedAt).ToListAsync();
        }

        public async Task<IEnumerable<LearningPlan>> GetByUserIdAndCategoryAsync(Guid userId, string category)
        {
            return await _dbSet.Where(p => p.UserId == userId && p.Category == category).ToListAsync();
        }

        public async Task<IEnumerable<LearningPlan>> GetByUserIdAndStatusAsync(Guid userId, string status)
        {
            return await _dbSet.Where(p => p.UserId == userId && p.Status == status).ToListAsync();
        }

        public async Task<IEnumerable<LearningPlan>> GetActiveAsync(Guid userId)
        {
            return await _dbSet.Where(p => p.UserId == userId && p.Status == "active").ToListAsync();
        }

        public async Task<Dictionary<string, int>> GetCategoryStatisticsAsync(Guid userId)
        {
            var plans = await _dbSet
                .Where(p => p.UserId == userId)
                .GroupBy(p => p.Category)
                .Select(p => new { Category = p.Key, Count = p.Count() })
                .ToListAsync();

            return plans.ToDictionary(p => p.Category, p => p.Count);
        }

        public async Task<Dictionary<string, int>> GetStatusStatisticsAsync(Guid userId)
        {
            var plans = await _dbSet
                .Where(p => p.UserId == userId)
                .GroupBy(p => p.Status)
                .Select(p => new { Status = p.Key, Count = p.Count() })
                .ToListAsync();

            return plans.ToDictionary(p => p.Status, p => p.Count);
        }

        public async Task<Dictionary<string, double>> GetProgressStatisticsAsync(Guid userId)
        {
            var plans = await _dbSet.Where(p => p.UserId == userId).ToListAsync();

            var result = new Dictionary<string, double>();
            if (plans.Any())
            {
                result["AverageProgress"] = plans.Average(p => p.ProgressPercentage);
                result["TotalPlans"] = plans.Count;
                result["CompletedPlans"] = plans.Count(p => p.Status == "completed");
                result["ActivePlans"] = plans.Count(p => p.Status == "active");
            }

            return result;
        }
    }

    /// <summary>
    /// 学习课程仓储实现
    /// </summary>
    public class LearningCourseRepository : Repository<LearningCourse>, ILearningCourseRepository
    {
        public LearningCourseRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<LearningCourse>> GetByPlanIdAsync(Guid planId)
        {
            return await _dbSet.Where(c => c.PlanId == planId).OrderBy(c => c.Order).ToListAsync();
        }

        public async Task<IEnumerable<LearningCourse>> GetByUserIdAsync(Guid userId)
        {
            var planIds = await _context.Set<LearningPlan>()
                .Where(p => p.UserId == userId)
                .Select(p => p.Id)
                .ToListAsync();

            return await _dbSet.Where(c => planIds.Contains(c.PlanId)).OrderByDescending(c => c.CreatedAt).ToListAsync();
        }

        public async Task<IEnumerable<LearningCourse>> GetByUserIdAndStatusAsync(Guid userId, string status)
        {
            var planIds = await _context.Set<LearningPlan>()
                .Where(p => p.UserId == userId)
                .Select(p => p.Id)
                .ToListAsync();

            return await _dbSet.Where(c => planIds.Contains(c.PlanId) && c.Status == status).ToListAsync();
        }

        public async Task<Dictionary<Guid, int>> GetCompletionRateByPlanAsync(IEnumerable<Guid> planIds)
        {
            var courses = await _dbSet
                .Where(c => planIds.Contains(c.PlanId))
                .ToListAsync();

            var result = new Dictionary<Guid, int>();
            foreach (var planId in planIds)
            {
                var planCourses = courses.Where(c => c.PlanId == planId).ToList();
                if (planCourses.Any())
                {
                    var completedCount = planCourses.Count(c => c.Status == "completed");
                    var totalCount = planCourses.Count;
                    result[planId] = totalCount > 0 ? (int)((double)completedCount / totalCount * 100) : 0;
                }
                else
                {
                    result[planId] = 0;
                }
            }

            return result;
        }
    }

    /// <summary>
    /// 学习记录仓储实现
    /// </summary>
    public class LearningRecordRepository : Repository<LearningRecord>, ILearningRecordRepository
    {
        public LearningRecordRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<LearningRecord>> GetByCourseIdAsync(Guid courseId)
        {
            return await _dbSet.Where(r => r.CourseId == courseId).OrderByDescending(r => r.StudyDate).ToListAsync();
        }

        public async Task<IEnumerable<LearningRecord>> GetByUserIdAsync(Guid userId)
        {
            var planIds = await _context.Set<LearningPlan>()
                .Where(p => p.UserId == userId)
                .Select(p => p.Id)
                .ToListAsync();

            var courseIds = await _context.Set<LearningCourse>()
                .Where(c => planIds.Contains(c.PlanId))
                .Select(c => c.Id)
                .ToListAsync();

            return await _dbSet.Where(r => courseIds.Contains(r.CourseId)).OrderByDescending(r => r.StudyDate).ToListAsync();
        }

        public async Task<IEnumerable<LearningRecord>> GetByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var planIds = await _context.Set<LearningPlan>()
                .Where(p => p.UserId == userId)
                .Select(p => p.Id)
                .ToListAsync();

            var courseIds = await _context.Set<LearningCourse>()
                .Where(c => planIds.Contains(c.PlanId))
                .Select(c => c.Id)
                .ToListAsync();

            return await _dbSet
                .Where(r => courseIds.Contains(r.CourseId) && r.StudyDate >= startDate && r.StudyDate <= endDate)
                .OrderBy(r => r.StudyDate)
                .ToListAsync();
        }

        public async Task<Dictionary<DateTime, double>> GetDailyStudyTimeAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow.Date;
            var startDate = endDate.AddDays(-days);

            var planIds = await _context.Set<LearningPlan>()
                .Where(p => p.UserId == userId)
                .Select(p => p.Id)
                .ToListAsync();

            var courseIds = await _context.Set<LearningCourse>()
                .Where(c => planIds.Contains(c.PlanId))
                .Select(c => c.Id)
                .ToListAsync();

            var records = await _dbSet
                .Where(r => courseIds.Contains(r.CourseId) && r.StudyDate >= startDate && r.StudyDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<DateTime, double>();
            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                var dayRecords = records.Where(r => r.StudyDate.Date == date.Date);
                result[date] = dayRecords.Sum(r => r.StudyDurationMinutes);
            }

            return result;
        }

        public async Task<Dictionary<Guid, double>> GetTotalStudyTimeByCourseAsync(IEnumerable<Guid> courseIds)
        {
            var records = await _dbSet
                .Where(r => courseIds.Contains(r.CourseId))
                .ToListAsync();

            var result = new Dictionary<Guid, double>();
            foreach (var courseId in courseIds)
            {
                var courseRecords = records.Where(r => r.CourseId == courseId).ToList();
                result[courseId] = courseRecords.Sum(r => r.StudyDurationMinutes);
            }

            return result;
        }
    }

    /// <summary>
    /// 成长日记仓储实现
    /// </summary>
    public class GrowthDiaryRepository : Repository<GrowthDiary>, IGrowthDiaryRepository
    {
        public GrowthDiaryRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<GrowthDiary>> GetByUserIdAsync(Guid userId)
        {
            return await _dbSet.Where(d => d.UserId == userId).OrderByDescending(d => d.DiaryDate).ToListAsync();
        }

        public async Task<IEnumerable<GrowthDiary>> GetByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _dbSet
                .Where(d => d.UserId == userId && d.DiaryDate >= startDate && d.DiaryDate <= endDate)
                .OrderBy(d => d.DiaryDate)
                .ToListAsync();
        }

        public async Task<GrowthDiary?> GetByUserIdAndDateAsync(Guid userId, DateTime date)
        {
            return await _dbSet.FirstOrDefaultAsync(d => d.UserId == userId && d.DiaryDate.Date == date.Date);
        }

        public async Task<IEnumerable<GrowthDiary>> GetByUserIdAndMoodAsync(Guid userId, string mood)
        {
            return await _dbSet.Where(d => d.UserId == userId && d.Mood == mood).OrderByDescending(d => d.DiaryDate).ToListAsync();
        }

        public async Task<IEnumerable<GrowthDiary>> GetByUserIdAndTagAsync(Guid userId, string tag)
        {
            return await _dbSet.Where(d => d.UserId == userId && d.Tags.Contains(tag)).OrderByDescending(d => d.DiaryDate).ToListAsync();
        }

        public async Task<Dictionary<string, int>> GetMoodStatisticsAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var diaries = await _dbSet
                .Where(d => d.UserId == userId && d.DiaryDate >= startDate && d.DiaryDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<string, int>();
            foreach (var diary in diaries)
            {
                if (!string.IsNullOrEmpty(diary.Mood))
                {
                    if (result.ContainsKey(diary.Mood))
                        result[diary.Mood]++;
                    else
                        result[diary.Mood] = 1;
                }
            }

            return result;
        }

        public async Task<Dictionary<string, int>> GetTagStatisticsAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var diaries = await _dbSet
                .Where(d => d.UserId == userId && d.DiaryDate >= startDate && d.DiaryDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<string, int>();
            foreach (var diary in diaries)
            {
                if (!string.IsNullOrEmpty(diary.Tags))
                {
                    var tags = diary.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var tag in tags)
                    {
                        var trimmedTag = tag.Trim();
                        if (result.ContainsKey(trimmedTag))
                            result[trimmedTag]++;
                        else
                            result[trimmedTag] = 1;
                    }
                }
            }

            return result;
        }

        public async Task<int> GetEntryCountAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            return await _dbSet
                .CountAsync(d => d.UserId == userId && d.DiaryDate >= startDate && d.DiaryDate <= endDate);
        }
    }

    /// <summary>
    /// 成长反思仓储实现
    /// </summary>
    public class GrowthReflectionRepository : Repository<GrowthReflection>, IGrowthReflectionRepository
    {
        public GrowthReflectionRepository(SheLifeDbContext context) : base(context)
        {
        }

        public async Task<IEnumerable<GrowthReflection>> GetByUserIdAsync(Guid userId)
        {
            return await _dbSet.Where(r => r.UserId == userId).OrderByDescending(r => r.ReflectionDate).ToListAsync();
        }

        public async Task<IEnumerable<GrowthReflection>> GetByUserIdAndDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            return await _dbSet
                .Where(r => r.UserId == userId && r.ReflectionDate >= startDate && r.ReflectionDate <= endDate)
                .OrderBy(r => r.ReflectionDate)
                .ToListAsync();
        }

        public async Task<GrowthReflection?> GetByUserIdAndDateAsync(Guid userId, DateTime date)
        {
            return await _dbSet.FirstOrDefaultAsync(r => r.UserId == userId && r.ReflectionDate.Date == date.Date);
        }

        public async Task<IEnumerable<GrowthReflection>> GetByUserIdAndTypeAsync(Guid userId, string type)
        {
            return await _dbSet.Where(r => r.UserId == userId && r.Type == type).OrderByDescending(r => r.ReflectionDate).ToListAsync();
        }

        public async Task<Dictionary<string, int>> GetTypeStatisticsAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var reflections = await _dbSet
                .Where(r => r.UserId == userId && r.ReflectionDate >= startDate && r.ReflectionDate <= endDate)
                .ToListAsync();

            var result = new Dictionary<string, int>();
            foreach (var reflection in reflections)
            {
                if (!string.IsNullOrEmpty(reflection.Type))
                {
                    if (result.ContainsKey(reflection.Type))
                        result[reflection.Type]++;
                    else
                        result[reflection.Type] = 1;
                }
            }

            return result;
        }

        public async Task<int> GetReflectionCountAsync(Guid userId, int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            return await _dbSet
                .CountAsync(r => r.UserId == userId && r.ReflectionDate >= startDate && r.ReflectionDate <= endDate);
        }
    }
}